//
//  ExamineResultViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/8/29.
//

#import "ExamineResultViewController.h"
#import "ExamineModel.h"
#import "joinScreenModel.h"
#import "TimeFrameShowView.h"
#import "ExamineTableViewCell.h"
#import "ExamineDetailsViewController.h"

@interface ExamineResultViewController ()<UITextFieldDelegate>


@property (nonatomic ,strong) NSMutableArray <ExamineModel *> * modelArray;

@property (nonatomic ,strong) UITextField * sstextfield;

@property (nonatomic ,strong) UIButton * textRemovebtn;

@property (nonatomic ,strong) UIView * makeView;
@property (nonatomic ,strong) UIScrollView * makescrollView;

@end

@implementation ExamineResultViewController

-(NSMutableArray<ExamineModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (UIView *)makeView {
    if(!_makeView){
        _makeView = [UIView new];
        _makeView.backgroundColor = UIColor.whiteColor;
        _makeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
        
        UILabel * ssls = [DTKTool labelWithText:@"历史搜索" andFont:kCFont(18) andTextColor:KcolorHex(@"#131416")];
        [_makeView addSubview:ssls];
        [ssls mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(kwt(15));
            make.top.offset(kwt(27));
        }];
        
        UIButton * scBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [scBtn setImage:[UIImage imageNamed:@"GBJL_delete"] forState:UIControlStateNormal];
        [scBtn addTarget:self action:@selector(deleteBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_makeView addSubview:scBtn];
        [scBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(kwt(-15));
            make.top.offset(kwt(27));
            make.width.height.offset(kwt(18));
        }];
        
        self.makescrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(kwt(15), kwt(65), kwt(345), kwt(400))];
        [_makeView addSubview:self.makescrollView ];
        
        
    }
    return _makeView;
}
- (void)back{
    self.model.queryParam = @"";
    [super back];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(170));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
   
    
    UIView * ssbjview = [UIView new];
    ssbjview.backgroundColor = UIColor.whiteColor;
    [DTKTool YJ:kwt(5) andView:ssbjview];
    [topview addSubview:ssbjview];
    [ssbjview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(50));
        make.right.offset(kwt(-60));
        make.centerY.offset(KTop/2);
        make.height.offset(37);
    }];
    
    UIImageView * ssimg = kimageView(@"program_search");
    [ssbjview addSubview:ssimg];
    [ssimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(15));
        make.centerY.offset(0);
        make.height.width.offset(kwt(16));
    }];
    
    UITextField * sstextfield = [UITextField new];
//    [sstextfield addTarget:self action:@selector(textFieldDidChangeValue:)  forControlEvents:UIControlEventEditingChanged];
    sstextfield.placeholder = @"请搜索";
    sstextfield.delegate = self;
    sstextfield.returnKeyType = UIReturnKeySearch;

    sstextfield.font = kFont(16);
    self.sstextfield = sstextfield;
    [ssbjview addSubview:sstextfield];
    [sstextfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(35));
        make.right.offset(kwt(-30));
        make.top.bottom.offset(0);
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldTextDidChangeOneCI:)
                                                name:UITextFieldTextDidChangeNotification
                                              object:sstextfield];
    
    UIButton * textRemovebtn = [UIButton buttonWithType:0];
    self.textRemovebtn = textRemovebtn;
    textRemovebtn.hidden = YES;
    textRemovebtn.addTarget(self,@selector(textRemovebtnClick));
    [textRemovebtn setBackgroundImage:[UIImage imageNamed:@"search_delete"] forState:UIControlStateNormal];
    [ssbjview addSubview:textRemovebtn];
    [textRemovebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kwt(23));
        make.right.offset(kwt(-10));
        make.centerY.offset(0);
    }];
    
    UIButton * ssbtn = [UIButton buttonWithType:0];
    ssbtn.addTarget(self,@selector(back));
    [ssbtn setTitle:@"取消" forState:UIControlStateNormal];
    [ssbtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    ssbtn.titleLabel.font = kCFont(16);
    [topview addSubview:ssbtn];
    [ssbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(kwt(60));
        make.centerY.equalTo(ssbjview);
        make.right.offset(0);
    }];
    
        
    
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#EBEDF0");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(topview.mas_bottom);
    }];
    [self addFooterView:^{
        [weakSelf addMoreData];
    }];
    [self addHeaderView:^{
        [weakSelf refreshingData];
    }];
    [self.view addSubview:self.makeView];
    
    [self addKeyboardNotifaction];
    [self refreshingData];
    [self.sstextfield becomeFirstResponder];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{ return YES; }
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.sstextfield.text.length < 1){
        return  [UIView new];
    }
    //加入你自定义的view
    UIView * noView = [UIView new];
    UIView * NewnoView = [UIView new];
//    NewnoView.backgroundColor = UIColor.whiteColor;
    [noView addSubview:NewnoView];
    [NewnoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(KSCREEN_WIDTH);
        make.center.offset(0);
        make.height.mas_offset(KSCREEN_HEIGHT);
    }];
    UIImageView * noImage = [UIImageView new];
    [noView addSubview:noImage];
    noImage.image = [UIImage imageNamed:@"no_search"];
    [noImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(-100);
    }];
    
    UILabel * noTitleLab = [UILabel new];
    [noView addSubview:noTitleLab];
    noTitleLab.text = @"暂无搜索记录\n换个关键词试试~";
    noTitleLab.numberOfLines = 2;
    noTitleLab.font = kFont(16);
    noTitleLab.textColor = [UIColor colorWithHexString:@"#262626"];
    [noTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(noImage.mas_bottom).offset(30);
        make.centerX.mas_offset(0);
    }];
    
    return noView;
}
///重新绘制蒙版
- (void)NewMakeViewUI{
    ///先清空
    [self.makescrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    ///获取所有数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray * array = [defaults objectForKey:@"ExamineResultViewController"];
    [defaults synchronize];
    
    CGFloat X = 0;
    CGFloat Y = 0;
    CGFloat MaxW = kwt(345);
    for (NSString * str in array) {
        ///先计算文字长度
        NSString * newStr = [NSString stringWithFormat:@"  %@  ",str];
        CGFloat strW = [newStr sizeWithAttributes:@{NSFontAttributeName:kFont(16)}].width;
        UILabel * lab = [DTKTool labelWithText:newStr andFont:kFont(16) andTextColor:KcolorHex(@"#5D5D5D")];
        lab.userInteractionEnabled = YES;
        UIGTapGestureRecognizer * tap = [[UIGTapGestureRecognizer alloc]initWithTarget:self action:@selector(labClick:)];
        tap.userInfo = @{@"str":str};
        [lab addGestureRecognizer:tap];
        lab.backgroundColor = KcolorHex(@"#F8F8F8");
        [DTKTool YJ:kwt(17) andView:lab];
        if(X + strW > MaxW){
            if(X == 0){///超出最多值切是开头位置
                lab.frame = CGRectMake(X, Y, MaxW, kwt(34));
                X = 0;
                Y += kwt(43);
            } else {
                X = 0;
                Y += kwt(43);
                lab.frame = CGRectMake(X, Y, strW, kwt(34));
                X += strW + kwt(10);
            }
        } else {
            lab.frame = CGRectMake(X, Y, strW, kwt(34));
            X += strW + kwt(10);
        }
        [self.makescrollView addSubview:lab];
    }
    //    self.makescrollView.contentSize = CGSizeMake(MaxW, Y + kwt(34));
    
}

/// 删除数据
- (void)deleteBtnClick{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除全部历史记录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //添加确定
    UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull   action) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:@[] forKey:@"ExamineResultViewController"];
        [defaults synchronize];
        [self NewMakeViewUI];
        [self.view endEditing:YES];
    }];
    [sureBtn setValue:[UIColor redColor] forKey:@"titleTextColor"];
    [alertVc addAction:cancelBtn];
    [alertVc addAction :sureBtn];
    [self presentViewController:alertVc animated:YES completion:nil];

}
///点击
- (void)labClick:(UIGTapGestureRecognizer *)tap{
    self.sstextfield.text = [tap.userInfo objectForKey:@"str"];
    self.model.queryParam =  self.sstextfield.text;
    ///进行一次搜索动作
    [self refreshingData];
    [self keyboardWillHide];
    [self.view endEditing:YES];
}
#pragma mark - 键盘监听
- (void)addKeyboardNotifaction{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];//键盘将要显示
}
#pragma mark - 键盘将要出现
- (void)keyboardWillShow:(NSNotification *)notification{
    [self NewMakeViewUI];
    [UIView animateWithDuration:0.25 animations:^{
        self.makeView.frame = CGRectMake(0, Knav_HeightX, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
    }];
}
- (void)keyboardWillHide{
    [UIView animateWithDuration:0.25 animations:^{
        self.makeView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
    }];
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"] && textField.text.length > 0){
        //        [SVProgressHUD showInfoWithStatus:@"搜索"];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray * array = [defaults objectForKey:@"ExamineResultViewController"];
        
        if(![array containsObject:textField.text]){
            NSMutableArray * newarray = [NSMutableArray arrayWithArray:array];
            [newarray addObject:textField.text];
            [defaults setObject:[NSArray arrayWithArray:newarray] forKey:@"ExamineResultViewController"];
        }
//        self.model.queryParam = textField.text;
//        [self refreshingData];
        [defaults synchronize];
        [self keyboardWillHide];
        [self.view endEditing:YES];
        return NO;
    }
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    self.textRemovebtn.hidden = (textField.text.length == 0);
//    self.model.queryParam = textField.text;
//    [self refreshingData];
//    [self.modelArray removeAllObjects];
//    [self.tableview reloadData];
    return YES;
}
-(void)textFieldTextDidChangeOneCI:(NSNotification *)notification
{
    UITextField *textfield=[notification object];
    if([textfield markedTextRange] == nil){
        NSLog(@"ssssss %@",textfield.text);
        self.model.queryParam = textfield.text;
        [self refreshingData];
        ///这里搜索
        if (textfield.text.length > 0){
            [self keyboardWillHide];
        } else {
            [self NewMakeViewUI];
            [UIView animateWithDuration:0.25 animations:^{
                self.makeView.frame = CGRectMake(0, Knav_HeightX, SCREEN_WIDTH, SCREEN_HEIGHT - Knav_HeightX);
            }];
        }
    }
    self.textRemovebtn.hidden = (self.sstextfield.text.length == 0);

}
- (void)textRemovebtnClick{
    self.sstextfield.text = @"";
    self.model.queryParam = @"";
    self.textRemovebtn.hidden = YES;
    [self.modelArray removeAllObjects];
    [self.tableview reloadData];
}
- (void)textFieldDidChangeValue:(UITextField *)sender{
    if(sender.markedTextRange == nil){
        NSLog(@"%@",sender.text);
        self.model.queryParam = sender.text;
        [self refreshingData];
    }
    self.textRemovebtn.hidden = (sender.text.length == 0);

}



- (void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadNewData];

}


- (void)loadNewData {
    if(self.sstextfield.text.length < 1){
        return;
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [self.model SHDict];
    [dict setObject:@(self.pageNo) forKey:@"pageNo"];
    [dict setObject:@(self.pageSize) forKey:@"pageSize"];
    
    [SCNetManger PostAuditGetAppAuditListWithDict:dict andCompetionHandlerBlock:^(HTTPArrBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            NSArray * array = [NSArray yy_modelArrayWithClass:ExamineModel.class json:model.result];
            [self.modelArray addObjectsFromArray:array];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableview.mj_footer endRefreshing];
            }
            [self.tableview.mj_header endRefreshing];
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}

//
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return kwt(100);
//}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerview = [UIView new];
    headerview.clipsToBounds = YES;
    UIView * btnview = [UIView new];
    MJWeakSelf
    btnview.addClickBlock(^{
        [weakSelf openTime];
    });
    [headerview addSubview:btnview];
    btnview.backgroundColor= UIColor.whiteColor;
    [DTKTool YJ:kwt(4) andView:btnview];
    [btnview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(10));
        make.height.offset(kwt(31));
    }];
    UILabel * time = [DTKTool labelWithText:@"-" andFont:kFont(16) andTextColor:KcolorHex(@"#222222")];
    [btnview addSubview:time];
    [time mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(kwt(11));
    }];
    
    UIImageView * img = kimageView(@"arrow_down");
    [btnview addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(kwt(-11));
        make.width.offset(kwt(12));
        make.height.offset(kwt(7));
        make.left.equalTo(time.mas_right).offset(kwt(11));
    }];
    if(self.model.startTime.length > 0){
        if([self.model.startTime isEqualToString:self.model.endTime]){
            time.text = self.model.startTime;
        } else {
            time.text = [NSString stringWithFormat:@"%@~%@",self.model.startTime,self.model.endTime];
        }
    } else {
        time.text = self.model.createTime;
    }
    return headerview;
    
}


- (void)openTime{
    MJWeakSelf
    if(self.model.startTime.length > 0){
        [TimeFrameShowView showviewWithTitle:@"请选择任务时间" andStartTime:self.model.startTime andEndTime:self.model.endTime andRightBlock:^(NSString * _Nonnull StartTime, NSString * _Nonnull EndTime) {
            weakSelf.model.endTime = EndTime;
            weakSelf.model.startTime = StartTime;
            [weakSelf refreshingData];
        } andCZBlock:^{
            weakSelf.model.endTime = @"";
            weakSelf.model.startTime = @"";
            [weakSelf refreshingData];
        }];
    } else{
        
        [BRDatePickerView showDatePickerWithMode:BRDatePickerModeYM title:@"请选择任务申请时间" selectValue:self.model.createTime minDate:nil maxDate:nil isAutoSelect:NO resultBlock:^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
            weakSelf.model.createTime = selectValue;
            [weakSelf refreshingData];
        }];
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(self.sstextfield.text.length < 1){
        return 0;
    }
    return kwt(50);
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.modelArray[indexPath.row].cellH;
//    return kwt(200);
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    
    ExamineTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ExamineTableViewCell"];
    if (cell == nil) {
        cell = [[ExamineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ExamineTableViewCell"];
    }
    cell.model = self.modelArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell ;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ExamineDetailsViewController * vc = [ExamineDetailsViewController new];
    vc.auditId = self.modelArray[indexPath.row].ID;
    [self.navigationController pushViewController:vc animated:YES];
}
@end
